<?php

namespace app\api\controller\v1;

use app\api\exception\BaseException;
use app\api\validate\ExpressScene;
use app\api\validate\GoodsScene;
use app\api\validate\RefundScene;
use app\api\validate\ReimburseScene;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Request;

/**
 * Class Refund
 * @package app\api\controller\v1
 * 报销
 *
 * 报销管理 和 退款管理合并为财务管理
 */
class Reimburse extends BaseException
{
    /**
     * 不需要登录方法
     */
    protected $noAuth = [''];

    //获取报销列表
    public function getReimburseList()
    {
        $data = Request::param();
        $search = [
        ];
        if (isset($data["sort"]) && $data["sort"] == "+id") {
            $order = ["id" => "asc"];
        } else {
            $order = ["id" => "desc"];
        }


        //员工只能看到自己的报销记录
        if ($this->user_type  == 4){
            $search[] = ["user_id", "=" , $this->user_id];
        }
        /**
         * 单一模糊查询开始
         */
        //联系人模糊查询
        if (isset($data["username"]) && !empty($data["username"])) {
            $search[] = ["username", "like", "%" . $data["username"] . "%"];
        }

        /**
         * 单一模糊查询结束
         */
        /**
         *多条件查询开始
         */
        //数据状态筛选查询
        //  if (isset($data["data_state"]) && $data["data_state"] != '') {
        array_push($search, ["data_state", "=", 1]);
        //}
        if (isset($data["status"]) && $data["status"] != '') {
            array_push($search, ["status", "=", $data["status"]]);
        }
        $reimburselist = Db::name("reimburse")->where($search)->order($order)->page($this->page_num, $this->page_limit)->select()->toArray();
        $count = Db::name("reimburse")->where($search)->count();
        foreach ($reimburselist as $key => $value){
            $imgsArray = explode(",",$reimburselist[$key]["imgs"]);
            $reimburselist[$key]["real_imgs"] = $imgsArray;
            if (count($imgsArray) != 0){
                for ($i = 0;$i < count($imgsArray);$i++){
                    $imgsArray[$i] = "http://" . $_SERVER['HTTP_HOST'] . $imgsArray[$i];
                }
            }
            $reimburselist[$key]["imgs"] = $imgsArray;

        }
        $list = [
            "total" => $count,
            "page" => $this->page_num,
            "limit" => $this->page_limit,
            "list" => $reimburselist
        ];
        //Db::name("account")->getLastSql();
        return self::Success($list, '获取成功', 200);
    }

    public function batchDelete()
    {
        $request = Request::param();
        $ids = explode(",", $request["ids"]);
        if (count($ids) != 0) {
            for ($i = 0; $i < count($ids); $i++) {
                $updateData = [
                    "data_state" => 0,
                    "update_time" => date("Y-m-d H:i:s", time()),
                ];
                Db::name("reimburse")->where(["id" => $ids[$i]])->update($updateData);
            }
        }
        return self::Success(null, "删除成功", 200);
    }

    public function addReimburseInfo()
    {
        $request = Request::param();
        try {
            validate(ReimburseScene::class)
                ->scene('add')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $userInfo = Db::name("account")->where(["user_id" => $this->user_id])->find();
        $insertData = [
            "reimburse_time" => isset($request["contact_name"]) ? $request["contact_name"] : date("Y-m-d H:i:s", time()),
            "price" => isset($request["price"]) ? $request["price"] : 0,
            "content" => isset($request["content"]) ? $request["content"] : "",
            "imgs" => isset($request["imgs"]) ? $request["imgs"] : "",
            "status" => 0,
            "username" => $userInfo["real_name"],
            "user_id" => $this->user_id,
            'create_time' => date("Y-m-d H:i:s", time()),
            'update_time' => date("Y-m-d H:i:s", time()),
            'data_state' => 1
        ];
        $result = Db::name("reimburse")->insert($insertData);
        if ($result) {
            return self::Success(null, "添加成功", 200);
        } else {
            return self::Error(null, '添加失败', 10002);
        }
    }

    //更改数据状态 删除
    public function batchUpdateState()
    {
        $request = Request::param();
        try {
            validate(ReimburseScene::class)
                ->scene('update_state')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $updateData = [
            "data_state" => $request["data_state"],
            "update_time" => date("Y-m-d H:i:s", time()),
        ];
        $check = Db::name("reimburse")->where(["id" => $request["id"]])->find();
        if ($check) {
            $result = Db::name("reimburse")->where(["id" => $request["id"]])->update($updateData);
            if ($result) {
                return self::Success(null, "操作成功", 200);
            } else {
                return self::Error(null, '操作失败', 10002);
            }
        } else {
            return self::Error(null, '数据不存在', 10002);
        }
    }

    //更新报销信息 只能财务人员进行更新
    public function updateReimburseInfo()
    {
        $request = Request::param();
        try {
            validate(ReimburseScene::class)
                ->scene('update')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $updateData = [
            "reimburse_time" => isset($request["contact_name"]) ? $request["contact_name"] : date("Y-m-d H:i:s", time()),
            "price" => isset($request["price"]) ? $request["price"] : 0,
            "content" => isset($request["content"]) ? $request["content"] : "",
            "imgs" => isset($request["imgs"]) ? $request["imgs"] : "",
            'update_time' => date("Y-m-d H:i:s", time()),
        ];
        $result = Db::name("reimburse")->where(["id" => $request["id"]])->update($updateData);
        if ($result) {
            return self::Success(null, "更新成功", 200);
        } else {
            return self::Error(null, '更新成功', 10002);
        }
    }

    public function updateReimburseStatus()
    {
        $request = Request::param();
        try {
            validate(ReimburseScene::class)
                ->scene('update_status')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $updateData = [
            "status" => $request["status"],
            "update_time" => date("Y-m-d H:i:s", time()),
        ];
        $check = Db::name("reimburse")->where(["id" => $request["id"]])->find();
        if ($check) {
            $result = Db::name("reimburse")->where(["id" => $request["id"]])->update($updateData);
            if ($result) {
                return self::Success(null, "操作成功", 200);
            } else {
                return self::Error(null, '操作失败', 10002);
            }
        } else {
            return self::Error(null, '数据不存在', 10002);
        }
    }


}